import axios from "axios";
import { useCounterStore } from '@/stores/counter.ts'
import router from '@/router/index.ts'
import { ElMessage } from "element-plus";
const store = useCounterStore();

const request = axios.create({
	baseURL: '/api',
	timeout: 600000
});


// axios的请求拦截器
request.interceptors.request.use(function (config) {
	// 发送请求之前需要做的
	// 将令牌存入到请求头中
	const loginAdmin = store.getLoginAdmin();
	if (loginAdmin && loginAdmin.token) {
		config.headers['token'] = loginAdmin.token
	}
	return config
}, function (error) {
	return Promise.reject(error)
})

// axios的响应拦截器

request.interceptors.response.use(
	(response) => {
		return response.data;
	},
	(error) => {
		console.log("error=" + error.response)
		if (error.response.status == 401) {
			router.push('/login')
			ElMessage.error("登录失效")
		}
		return Promise.reject(error)
	}
)
export default request